//
//  HJSelectFile.m
//  KaiChat
//
//  Created by lx on 2023/10/25.
//

#import "HJSelectFile.h"
//#import <Photos/Photos.h>
//#import <PhotosUI/PhotosUI.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "TZImagePickerController.h"

//#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_14_0

@interface HJSelectFile()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, TZImagePickerControllerDelegate>


@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, copy) void (^selectPhotoComplete)(NSArray<UIImage *> *photos,NSArray *assets);
@property (nonatomic, copy) void (^openCameraComplete)(id mediaObject);


@end


@implementation HJSelectFile

- (instancetype)init {
    if (self = [super init]) {
        _queue = dispatch_queue_create("SELECTFILEQUEUE", DISPATCH_QUEUE_CONCURRENT);
        _group = dispatch_group_create();
    }
    return self;
}


- (void)selectPhotoInController:(UIViewController *)controller complete:(void (^)(NSArray<UIImage *> *photos,NSArray *assets))complete {
    [self selectPhotoInController:controller maxCount:9 complete:complete];
}

- (void)selectPhotoInController:(UIViewController *)controller maxCount:(NSInteger)count complete:(void (^)(NSArray<UIImage *> *photos,NSArray *assets))complete {
    self.selectPhotoComplete = complete;
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowEditVideo = NO;
    imagePickerVc.allowCameraLocation = YES;
    imagePickerVc.pickerDelegate = self;
    imagePickerVc.preferredLanguage = @"en";
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor tj_mainColor];
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.allowPreview = YES;
    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingMultipleVideo = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
    imagePickerVc.iconThemeColor = [UIColor tj_mainColor];
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [controller presentViewController:imagePickerVc animated:YES completion:nil];
    
    [HJTools tool].imagePickerController = imagePickerVc;
}

- (void)selectImageInController:(UIViewController *)controller maxCount:(NSInteger)count complete:(void (^)(NSArray<UIImage *> *photos,NSArray *assets))complete {
    self.selectPhotoComplete = complete;
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowEditVideo = NO;
    imagePickerVc.allowCameraLocation = YES;
    imagePickerVc.pickerDelegate = self;
    imagePickerVc.preferredLanguage = @"en";
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor tj_mainColor];
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.allowPreview = YES;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
    imagePickerVc.iconThemeColor = [UIColor tj_mainColor];
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [controller presentViewController:imagePickerVc animated:YES completion:nil];
    
    [HJTools tool].imagePickerController = imagePickerVc;
}

- (void)selectVideoInController:(UIViewController *)controller complete:(void (^)(NSArray<UIImage *> *photos,NSArray *assets))complete {
    
    self.selectPhotoComplete = complete;
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowEditVideo = NO;
    imagePickerVc.allowCameraLocation = YES;
    imagePickerVc.pickerDelegate = self;
    imagePickerVc.preferredLanguage = @"en";
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor tj_mainColor];
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.allowPreview = YES;
    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowPickingImage = NO;
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
    imagePickerVc.iconThemeColor = [UIColor tj_mainColor];
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [controller presentViewController:imagePickerVc animated:YES completion:nil];
    [HJTools tool].imagePickerController = imagePickerVc;
    
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    if (self.selectPhotoComplete) {
        self.selectPhotoComplete(photos, assets);
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    
    if (self.selectPhotoComplete) {
        self.selectPhotoComplete(@[coverImage], @[asset]);
    }
}



- (void)openCameraInController:(UIViewController *)controller complete:(void (^)(id mediaObject))complete {
    
    
    self.openCameraComplete = complete;
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        NSLog(@"sorry, no camera or camera is unavailable.");
        return;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    //    imagePickerController.videoMaximumDuration = 15;
    //        imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    
    //    imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie];
    //    imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    //    imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    imagePickerController.allowsEditing = NO;
    //    imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    //    imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    [controller presentViewController:imagePickerController animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    if (!_openCameraComplete) {
        return;
    }
    
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        [picker dismissToRootViewController:YES completion:^{
            self.openCameraComplete(originalImage);
        }];
        return;
    }
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        [picker dismissToRootViewController:YES completion:^{
            self.openCameraComplete(mediaURL);
        }];
        
    }
    
}

- (BOOL)isAssetCanBeSelected:(PHAsset *)asset {
        
     __block BOOL canSelected = YES;
    
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        
        PHVideoRequestOptions* options = [[PHVideoRequestOptions alloc] init];
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        options.networkAccessAllowed = YES;
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            if ([avAsset isKindOfClass:[AVURLAsset class]]) {
                AVURLAsset *urlAsset = (AVURLAsset *)avAsset;
                NSError *fileSizeError;
                
                NSURL *URL = [(AVURLAsset *)avAsset URL];
                NSData *fileData = [NSData dataWithContentsOfURL:URL];
                uint64_t length = fileData.length;
                NSLog(@"fileData.length = %lld", length);
                if (length > 500 * 1024 * 1024) {
                    canSelected = NO;
                }
            }
            dispatch_semaphore_signal(semaphore);
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    }
    
    if (canSelected == NO) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"The selected file cannot exceed 500 MB" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:[NSBundle tz_localizedStringForKey:@"OK"] style:UIAlertActionStyleDefault handler:nil]];
        [[HJTools tool].imagePickerController presentViewController:alertController animated:YES completion:nil];
    }
    
    return canSelected;
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissToRootViewController:YES completion:nil];
    
}

@end
